import allure

from core.rest_client_new import RestClient
from utils.AssertUtil import AssertUtil
from utils.ExtractUtil import ExtractUtil
import os


class ApiService:

    def __init__(self):
        self.session = RestClient()
        self.extract = ExtractUtil()
        self.file_path = os.path.join(os.path.dirname(os.path.dirname(os.path.realpath(__file__))), "file/")

    def handle_case(self, test_data, login_token=None):
        # 获取host
        host = self.extract.extract_host(test_data['request_info']['host'])
        # 获取url
        url = self.extract.extract_url(test_data['request_info']['url'])
        # 获取method
        method = test_data['request_info']['method']
        # 获取headers
        headers = test_data['request_info'].pop("headers", {})  # 如果没有header时做特殊处理
        # 判断是否有login_token,把获取到 yaml文件中的header和login_token拼接
        if login_token:
            headers.update(login_token)
        # 获取title
        allure_title = test_data['request_info']['case_title']
        # 给allure报告定义用例标题
        allure.dynamic.title(allure_title)
        # 获取case_info
        case_info = test_data['case_info']
        # 获取validate 加pop从case_info里面去掉validate
        validate = case_info.pop('validate', None)  # 默认返回None
        # 获取extract
        extract = case_info.pop('extract', None)  # 没有的时候返回 NOne
        case_info = self.extract.extract_case(case_info)
        # 获取文件上传
        file, files = case_info.pop('files', None), None
        if file is not None:
            for fk, fv in file.items():  # 如果file里面有内容进行循环，最后得到结果files:{file:('upload.jpeg')
                files = {fk: (fv, open(self.file_path + fv, mode='rb'), 'image/jpeg')}  # 固定file文件格式 参照read_file方法
        res = self.session.do_request(url=host + url, method=method, headers=headers, files=files, **case_info)
        # 写入extract_yaml文件中
        self.extract.extract_data(res, extract)
        AssertUtil().validate_response(res, validate)
        return res
